function initTab() {
    let session = document.querySelector('.main .left .tab .session')
    let friend = document.querySelector('.main .left .tab .friend')
    let sessionList = document.querySelector('.main .left .session-list')
    let friendList = document.querySelector('.main .left .friend-list')
    session.onclick = function() {
        session.style.backgroundImage = 'url(./images/对话1.png)'
        friend.style.backgroundImage = 'url(./images/朋友.png)'
        sessionList.classList = 'list session-list'
        friendList.classList = 'list friend-list hiden'
    }

    friend.onclick = function() {
        session.style.backgroundImage = 'url(./images/对话.png)'
        friend.style.backgroundImage = 'url(./images/朋友1.png)'
        sessionList.className = 'list session-list hiden'
        friendList.classList = 'list friend-list'
    }
}

initTab()

let address = 'http://127.0.0.1:8080/'
// let address = 'http://123.57.1.114:8080/'

let imageCache = {}

function getUserInfo() {
    $.ajax({
        method: 'get',
        url: '/user/getUserInfo',
        success: function(body) {
            if (body.status == 200 && body.data != null) {
                let name = document.querySelector('.main .left .user span')
                let pic = document.querySelector('.main .left .user .picture')
                // let pic = document.querySelector('.main .left .user .picture')
                name.innerHTML = body.data.username
                name.setAttribute('userId',body.data.userId)
                name.setAttribute('image',body.data.image)
                downloadFile(address + 'user/getUserPic?fileName=' + body.data.image,pic)
                // console.dir(ret)
                // pic.style.backgroundImage = ret
            }else {
                alert(body.data.message)
            }
        },
        error: function(body) {
            if (body.status == 401) {
                alert('您当前未登录，请登陆后再试吧！')
                location.href = 'login.html'
            }
        }
    });
}

getUserInfo()

function downloadFile(url,div) {  
    let name = url.substring(url.indexOf('=') + 1);
    if (imageCache[name]) {
        div.style.backgroundImage = 'url(' + imageCache[name].src + ')'
        return
    }
    fetch(url, {  
        method: 'post', // 或者其他HTTP方法，根据你的Spring后端配置  
        // 这里不需要设置Content-Type，因为它是请求头，而我们是在响应中接收数据  
        // 但可以添加其他必要的请求头，如认证信息等  
        headers: {  
            // 示例：'Authorization': 'Bearer your_token_here'  
        },  
        // 告诉浏览器我们期望的响应类型是一个Blob  
        responseType: 'blob'  
    })  
    .then(response => {  
        // 检查响应是否成功  
        if (!response.ok) {  
            throw new Error('Network response was not ok');  
        }  
        // 返回Blob对象  
        return response.blob();  
    })  
    .then(blob => {  
        // 创建一个指向该Blob的URL  
        const url = window.URL.createObjectURL(blob); 
        let image = new Image()
        image.src = url
        image.onload = () => {
            imageCache[name] = image
        }
        div.style.backgroundImage = 'url(' + url + ')' 
  
        // 清理工作  
        // window.URL.revokeObjectURL(url);  
        // document.body.removeChild(a);  
    })  
    .catch(error => {  
        console.error('There has been a problem with your fetch operation:', error);  
    });  
} 

function getSessionList() {
    console.log('执行getsessionlist')
    fetch(address + 'session/getSessionList')
        .then(response => {
            if (!response.ok) {
                return
            }
            return response.json()
        })
        .then(data => {
            let sessionList = document.querySelector('.main .left .session-list ul')
                sessionList.innerHTML = ''
                for (let session of data.data) {
                    let li = document.createElement('li')
                    if (session.lastMessage == null) {
                        session.lastMessage = '' 
                    }
                    if (session.lastMessage.lenth > 10) {
                        session.lastMessage = session.lastMessage.substring(0,10) + '...';
                    }
                    let now = new Date();
                    let time = now.toLocaleDateString()
                    let lastTime = session.lastTime
                    let now2 = new Date(lastTime.substring(0,lastTime.indexOf(' ')))
                    let tmp = now2.toLocaleDateString()
                    if (tmp == time) {
                        session.lastTime = lastTime.substring(lastTime.indexOf(' ') + 1)
                    }else {
                        session.lastTime = lastTime.substring(0,lastTime.indexOf(' '))
                    }
                    getTodoMessage(session,li)
                }
            getNewFriend()
        })
}


function getTodoMessage(session,li) {
    fetch(address + 'todo/getCountByUserIdAndSessionId?sessionId=' + session.sessionId)
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        console.dir(response)
        return response.json()
    })
    .then(data => {
        if (data.data == 0) {
            data.data = ''
        }
        li.innerHTML = '<div class="left"></div>' + 
                '<div class="right"><div class="top">' +
                '<span id="name">' + session.friendName +
                '</span><span id="blank"></span>' + 
                '<span id="time">' + session.lastTime +
                '</span></div>' + '<div class="bottom">' +
                '<div class="content"><p>' + session.lastMessage + '</p></div>' +
                '<div class="todo">' + data.data + '</div>' + '</div></div>'
        if (data.data == null || data.data == '' || data.data == 'null') {
            li.querySelector('.bottom .todo').innerHTML = ''
            li.querySelector('.bottom .todo').style.width = '0px'
        }
        downloadFile(address + 'user/getUserPic?fileName=' + session.image,li.querySelector('.left'))
        li.setAttribute('sessionId',session.sessionId)
        let sessionList = document.querySelector('.main .left .session-list ul')
        sessionList.appendChild(li)
        li.onclick = function() {
            if (li.className == 'selected') return
            setHighLight(li)
            showMessage(session.friendName,session.sessionId)
        }
    })
}

getSessionList()
// function getTodoCount() {
//     console.log('执行gettodocount')
//     $.ajax({
//         method: 'get',
//         url: '/todo/getTodoMessage',
//         success: function(body) {
//             let sessionList = document.querySelectorAll('.main > .left .session-list ul li')
//             console.log(sessionList)
//             for (let session of sessionList) {
//                 for (let message of body.data) {
//                     if (session.getAttribute('sessionId') == message.sessionId) {
//                         if (message.count != 0) {
//                             console.log(message.count)
//                             session.querySelector('.bottom .todo').innerHTML = message.count
//                         }else {
//                             session.querySelector('.bottom .todo').style.width = '0px'
//                         }
//                     }
//                 }
//             }
//         },
//         error: function(body) {
//             alert('出现错误')
//         }
//     });
// }
// getSessionList().then(getTodoCount)


function setHighLight(li) {
    let lis = document.querySelectorAll('.main .left .session-list li')
    for (let l of lis) {
        if (l == li) {
            l.className = 'selected'
            l.querySelector('.top').classList = 'top selected'
            l.querySelector('.bottom').classList = 'bottom selected'
            l.querySelector('.bottom .todo').innerHTML = ''
            l.querySelector('.bottom .todo').style.width = '0px'
            l.querySelector('.bottom .todo').classList = 'todo selected'
        }else {
            l.className = ''
            l.querySelector('.top').classList = 'top'
            l.querySelector('.bottom').classList = 'bottom'
            l.querySelector('.bottom .todo').classList = 'todo'
        }
    }
}

function getFriendList() {
    $.ajax({
        method: 'get',
        url: '/friend/getFriendList',
        success: function(body) {
            if (body.status == 200 && body.data != null) {
                let friendList = document.querySelector('.main .left .friend-list')
                friendList.innerHTML = ''
                for (let session of body.data) {
                    let li = document.createElement('li')
                    li.innerHTML = '<div class="left"></div>' + 
                        '<div class="right"><span>' + session.friendName
                        + '</span></div>'
                    downloadFile(address + 'user/getUserPic?fileName=' + session.image,li.querySelector('.left'))
                    friendList.appendChild(li)
                    li.onclick = function() {
                        clickFriend(session.friendName)
                    }
                }
                let li = document.createElement('li')
                li.innerHTML = '<div class="left friend"></div>' + 
                        '<div class="right"><span>' + '点击添加朋友'
                        + '</span></div>'
                friendList.insertBefore(li,friendList.children[0])
                li.onclick = function() {
                    addNewFriend()
                }
            }
        }
    });
}

getFriendList();

function addNewFriend() {
    console.log('添加好友')
    let user = document.querySelector('.main > .left .user span')
    let name = prompt('请输入好友用户名')
    let req = {
        type: 'friend',
        fromId: user.getAttribute('userId'),
        fromName: user.innerHTML,
        content: name
    }
    websocket.send(JSON.stringify(req))
}

function clickFriend(userName) {
    let sessionList = document.querySelectorAll('.main .left .session-list li')
    let sessionUl = document.querySelector('.main .left .session-list ul')
    let sessionTab = document.querySelector('.main .left .tab .session')
    for (let session of sessionList) {
        console.dir(session.querySelector('.top #name'))
        if (session.querySelector('.top #name').innerHTML == userName) {
            sessionUl.insertBefore(session,sessionUl.children[0])
            setHighLight(session)
            showMessage(userName,session.getAttribute('sessionId'))
            sessionTab.click()
            return
        }
    }
    $.ajax({
        method: 'post',
        url: '/session/createSession',
        data: {friendName: userName},
        success: function(body) {
            let li = document.createElement('li')
            li.innerHTML = '<div class="left"></div>' + 
                    '<div class="right"><div class="top">' +
                    '<span id="name">' + userName +
                    '</span><span id="blank"></span>' + 
                    '<span id="time"></span></div>' 
                     + '<div class="bottom">' +
                    '<div class="content"><p>' + '</p></div>' +
                    '<div class="todo"></div>'
                    '</div></div>'
                    downloadFile(address + 'user/getUserPic?fileName=' + body.data.image,li.querySelector('.left'))
                    li.setAttribute('sessionId',body.data.sessionId)
                    sessionUl.insertBefore(li,sessionUl.children[0])
                    li.onclick = function() {
                        setHighLight(li)
                    }
                    li.click()
                    showMessage(userName,body.data.sessionId)
                }
    });
    sessionTab.click()  
}

function showMessage(friendName,sesionId) {
    let name = document.querySelector('.main > .right .title span')
    name.innerHTML = friendName
    $.ajax({
        method: 'post',
        url: '/message/getMessageInfos',
        data: {sessionId: sesionId},
        success: function(body) {
            if (body.status == 200 && body.data != null) {
                let messageShow = document.querySelector('.main > .right .message-show')
                let userId = document.querySelector('.main .left .user span').getAttribute('userId')
                messageShow.innerHTML = ''
                for (let message of body.data) {
                    let li = document.createElement('div')
                    if (message.fromId == userId) {
                        li.innerHTML = '<div class="message message-right">' +
                        '<div class="box"><div class="left"><p>' + message.content +
                        '</p></div>' + '<div class="right image"></div></div>'
                        downloadFile(address + 'user/getUserPic?fileName=' + message.image,li.querySelector('.right'))
                    }else {
                        li.innerHTML = '<div class="message message-left">' +
                        '<div class="box"><div class="left image"></div>' +
                        '<div class="right"><p>' + message.content + '</p>' +
                        '</div></div>'
                        downloadFile(address + 'user/getUserPic?fileName=' + message.image,li.querySelector('.left'))
                    }
                    if (message.content.length >= 40) {
                        li.querySelector('p').style.width = '650px'
                    }
                    messageShow.appendChild(li)
                }
                scrollToBottom(messageShow)
            }
        }
    });

}

function scrollToBottom(elem) {
    elem.scrollTo(0,elem.scrollHeight - elem.offsetHeight)
}

let websocket = new WebSocket('ws://' + location.host + '/send')

websocket.onmessage = function(e) {
    let message = JSON.parse(e.data)
    if (e.type == 'friend') {
        let li = document.createElement('li')
        let sessionList = document.querySelector('.main > .left .session-list ul')
        li.innerHTML = '<div><p>' + message.fromName + '向你发送了好友申请' +
        '</p><button id="yes">同意</button><button id="no">拒绝</button>'
        sessionList.insertBefore(li,sessionList.children[0])
    }else {
        let sessionList = document.querySelectorAll('.main > .left .session-list li')
        let sessions = document.querySelector('.main > .left .session-list ul')
        for (let session of sessionList) {
            if (session.getAttribute('sessionId') == message.sessionId) {
                session.querySelector('.right .bottom p').innerHTML = message.content
                session.querySelector('.right .top #time').innerHTML = message.postTime
                sessions.insertBefore(session,sessions.children[0])
                session.click()
            }
        }
        let div = document.createElement('div')
        div.innerHTML = '<div class="message message-left">' +
                        '<div class="box"><div class="left image"></div>' +
                        '<div class="right"><p>' + message.content + '</p>' +
                        '</div></div>'
        downloadFile(address + 'user/getUserPic?fileName=' + message.image,div.querySelector('.left'))
    }
}

let sendBtn = document.querySelector('.main > .right .control button')
sendBtn.onclick = function() {
    let content = document.querySelector('.main > .right #input')
    let user =  document.querySelector('.main > .left .user span')
    if (content.value == '') return;
    let now = new Date()
    let time = now.toLocaleString()
    time = time.replaceAll('/','-')
    let session = document.querySelector('.main > .left .session-list .selected')
    let req = {
        fromId: user.getAttribute('userId'),
        image: user.getAttribute('image'),
        content: content.value,
        postTime: time,
        sessionId: session.getAttribute('sessionId')
    }
    websocket.send(JSON.stringify(req))
    let li = document.createElement('div')
    let image = document.querySelector('.main > .left .user span').getAttribute('image')
    li.innerHTML = '<div class="message message-right">' +
                    '<div class="box"><div class="left"><p>' + content.value +
                    '</p></div>' + '<div class="right image"></div></div>'
    downloadFile(address + 'user/getUserPic?fileName=' + image,li.querySelector('.right'))
    let messageShow = document.querySelector('.main > .right .message-show')
    messageShow.appendChild(li)
    session.querySelector('#time').innerHTML = now.toLocaleTimeString()
    session.querySelector('.bottom p').innerHTML = content.value
    content.value = ''
    scrollToBottom(messageShow)
}

let searchBtn = document.querySelector('.main > .left .search button')
searchBtn.onclick = function() {
    let content = document.querySelector('.main > .left .search input')
    if (content.value == '') return
    fetch(address + 'session/getSessionIdByUsername?username=' + content.value)
    .then(response => {
        if (!response.ok) {
            return
        }
        return response.json()
    })
    .then(data => {
        if (data.status == 200 && data.data != null) {
            content.value = ''
            let set = new Set()
            for (let sessionId of data.data) {
                set.add(sessionId + '')
            }
            let lis = document.querySelectorAll('.main > .left .session-list li')
            let sessionList = document.querySelector('.main > .left .session-list')
            for (let li of lis) {
                console.log(typeof(li.getAttribute('sessionId')))
                if (set.has(li.getAttribute('sessionId'))) {
                    sessionList.insertBefore(li,sessionList.children[0])
                }
            }
        }else {
            alert(data.message)
        }
    })
}

function getNewFriend() {
    $.ajax({
        method: 'get',
        url: '/newFriend/getNewFriend',
        success: function(body) {
            if (body.status == 200 && body.data != null) {
                console.log(body.data)
                let sessionList = document.querySelector('.main > .left .session-list ul')
                for (let friend of body.data) {
                    let li = document.createElement('li')
                    li.className = 'newFriend'
                    li.innerHTML = '<div><div class="top"><span id="fromName">' + friend.fromName + '向你发送了好友申请' +
                    '</span></div>' + '<div class="bottom"><span id="addTime">' + friend.postTime + '</span><button id="yes">同意</button>' +
                    '<button id="no">拒绝</button></div></div>'
                    sessionList.insertBefore(li,sessionList.children[0])
                    li.querySelector('#yes').onclick = function() {
                        allow(friend.fromId,friend.toId,li)
                    }
                    li.querySelector('#no').onclick = function() {
                        reject(friend.fromId,friend.toId,li)
                    }
                }
            }
        }
    });
} 

function allow(fromId,toId,li) {
    console.log(toId)
    $.ajax({
        method: 'post',
        url: '/friend/addFriend',
        data: {
            userId: fromId,
            friendId: toId
        },
        success: function(body) {
            if (body.status == 200 && body.data != null) {
                let sessionList = document.querySelector('.main > .left .session-list ul')
                sessionList.remove(li)
                getFriendList()
            }else {
                alert(body.message)
            }
        }
    });
}

function reject(fromId,toId,li) {
    $.ajax({
        method: 'post',
        url: '/newFriend/delete',
        data: {
            fromId: fromId,
            toId: toId
        },
        success: function(body) {
            if (body.status == 200 && body.data != null) {
                
            }else {
                alert(body.message)
            }
            let sessionList = document.querySelector('.main > .left .session-list ul')
            sessionList.remove(li)
        }
    });
}
